package com.ruoyi.web.controller.system;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.DeviceProperty;
import com.ruoyi.system.domain.DevicePropertyValue;
import com.ruoyi.system.domain.PointCheck;
import com.ruoyi.system.domain.PointCheckDate;
import com.ruoyi.system.domain.ValidationGroups.*;
import com.ruoyi.system.domain.vo.QueryVo;
import com.ruoyi.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/system/point_check")
public class PointCheckController extends BaseController {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private IPointCheckService pointCheckService;
    @Autowired
    private IPointCheckDateService pointCheckDateService;
    @Autowired
    private ICustomPermissionService customPermissionService;
    @Autowired
    private IProjectAuthorizeService projectAuthorizeService;
    @Autowired
    private ISysUserService sysUserService;
    /**
     * 现场工程师
     */
    @Value("${sysUser.sceneRoleId:102}")
    private Long sceneRoleId;

    /**
     * 巡检工角色Id
     */
    @Value("${sysUser.inspectorRoleId:104}")
    private Long inspectorRoleId;

    /**
     * 点检计划分页查询
     */
    @PreAuthorize("@ss.hasPermi('system:point:check:list')")
    @GetMapping("/list")
    public TableDataInfo list(@Validated(Select.class) PointCheck pointCheck) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        boolean flag = sysDeptService.checkIsCustomer(loginUser.getUser().getDeptId());
        if (flag){
            Long customerId = sysDeptService.getCustomerId(loginUser.getUser().getDeptId());
            if (pointCheck.getDeptId() != null){
                if (customerId.compareTo(pointCheck.getDeptId()) != 0){
                    customerId = pointCheck.getDeptId();
                }
            }
            pointCheck.setDeptId(customerId);
        }
        startPage();
        List<PointCheck> pointChecks = pointCheckService.queryList(pointCheck);
        //客户公司过滤项目合同号
        if (flag && CollUtil.isNotEmpty(pointChecks)){
            pointChecks.forEach(a ->{
                a.setProjectCode(null);
            });
        }
        return getDataTable(pointChecks);
    }

    /**
     * 获取点检计划详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:pointCheck:query')")
    @GetMapping(value = "/get_info")
    public AjaxResult getInfo(Integer id) {
        PointCheck param = new PointCheck();
        param.setId(id);
        PointCheck pointCheck = pointCheckService.getOne(param);
        return AjaxResult.success(pointCheck);
    }

    /**
     * 新增点检计划
     */
    @PreAuthorize("@ss.hasPermi('system:point:check:add')")
    @Log(title = "点检计划", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody @Validated(Create.class) PointCheck pointCheck) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 设置companyId
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        pointCheck.setCompanyId(companyId);
        pointCheck.setCreateBy(loginUser.getUsername());
        pointCheck.setCreateTime(new Date());
        pointCheckService.checkExecutorStatus(pointCheck);
        //验证属性名称是否重复
        pointCheckService.checkIsExist(pointCheck);
        if (pointCheckService.add(pointCheck)) {
            Integer id = pointCheck.getId();
            return AjaxResult.success(id);
        }
        return AjaxResult.error("添加失败");
    }

    @PreAuthorize("@ss.hasPermi('system:point:check:add')")
    @GetMapping("/add_task")
    public AjaxResult addTask( Integer id) {
        PointCheck pointCheck = new PointCheck();
        pointCheck.setId(id);
        if (pointCheckService.getTask(pointCheck)) {
            return AjaxResult.success("添加成功");
        }
        return AjaxResult.error("添加失败");
    }

    /**
     * 修改点检计划
     */
    @PreAuthorize("@ss.hasPermi('system:point:check:edit')")
    @Log(title = "点检计划", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody @Validated(Update.class) PointCheck pointCheck) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 设置companyId
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        pointCheck.setCompanyId(companyId);
        pointCheck.setCreateBy(loginUser.getUsername());
        pointCheck.setCreateTime(new Date());
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //验证是否有操作权限
        projectAuthorizeService.checkPointCheckOperationStatus(user,pointCheck.getId());
        pointCheckService.checkExecutorStatus(pointCheck);
        //验证名称和系统名称是否重复
        pointCheckService.checkIsExist(pointCheck);
        if (pointCheckService.update(pointCheck)) {
            return AjaxResult.success("修改成功");
        }
        return AjaxResult.error("修改失败");
    }

    /**
     * 删除点检计划
     */
    @PreAuthorize("@ss.hasPermi('system:point:check:delete')")
    @Log(title = "点检计划", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable @NotNull(message = "id不能为null") Integer id) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //验证是否有操作权限
        projectAuthorizeService.checkPointCheckOperationStatus(user,id);
        PointCheck pointCheck = new PointCheck();
        pointCheck.setId(id);
        if (pointCheckService.delete(pointCheck)) {
            return AjaxResult.success("删除成功");
        }
        return AjaxResult.error("删除失败");
    }

    /**
     * 添加计划时间
     *
     * @param pointCheck
     * @return
     */
    @PostMapping("/bind_point_check_date")
    public AjaxResult addPointCheckDate(@RequestBody PointCheck pointCheck) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 设置companyId
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        pointCheck.setCompanyId(companyId);
        pointCheck.setCreateBy(loginUser.getUsername());
        pointCheckService.addPointCheckDate(pointCheck);
        return AjaxResult.success("添加成功");
    }
    @PreAuthorize("@ss.hasPermi('system:point:check:date:add')")
    @PostMapping("/add_check_date")
    public AjaxResult addCheckDate(@RequestBody @Validated(Create.class) PointCheckDate pointCheckDate){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 设置companyId
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        if(DateUtil.parse(pointCheckDate.getStart(),"HH:mm").compareTo(DateUtil.parse(pointCheckDate.getEnd(), "HH:mm")) > 0){
            throw new CustomException("开始时间不能大于或等于结束时间");
        }
        //验证是否有操作权限
        projectAuthorizeService.checkPointCheckOperationStatus(loginUser.getUser(),pointCheckDate.getPointId());
        pointCheckDate.setCompanyId(companyId);
        pointCheckDate.setCreateBy(loginUser.getUsername());
        pointCheckDate.setCreateTime(new Date());
        if (pointCheckDateService.add(pointCheckDate)){
            return AjaxResult.success("添加成功");
        }
        return AjaxResult.error("添加失败");
    }
    @PreAuthorize("@ss.hasPermi('system:point:check:date:edit')")
    @PostMapping("/update_check_date")
    public AjaxResult updateCheckDate(@RequestBody @Validated(Update.class) PointCheckDate pointCheckDate){
        if(DateUtil.parse(pointCheckDate.getStart(),"HH:mm").compareTo(DateUtil.parse(pointCheckDate.getEnd(), "HH:mm")) > 0){
            throw new CustomException("开始时间不能大于或等于结束时间");
        }
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //验证是否有操作权限
        projectAuthorizeService.checkPointCheckOperationStatus(user,pointCheckDate.getPointId());
        if (pointCheckDateService.update(pointCheckDate)){
            return AjaxResult.success("修改成功");
        }
        return AjaxResult.error("修改失败");
    }
    @PreAuthorize("@ss.hasPermi('system:point:check:date:delete')")
    @DeleteMapping("/delete_check_date/{id}")
    public AjaxResult deleteCheckDate(@PathVariable @NotNull(message = "id不能为null") Integer id){
        PointCheckDate checkDate = new PointCheckDate();
        checkDate.setId(id);
        List<PointCheckDate> pointCheckDates = pointCheckDateService.queryList(checkDate);
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //验证是否有操作权限
        Integer pointId = pointCheckDates.get(0).getPointId();
        projectAuthorizeService.checkPointCheckOperationStatus(user,pointId);
        if (pointCheckDateService.delete(checkDate)){
            return AjaxResult.success("删除成功");
        }
        return AjaxResult.error("删除失败");
    }

    @PreAuthorize("@ss.hasPermi('system:point:check:user:info')")
    @GetMapping("/query_user_info")
    public AjaxResult queryUserInfo(){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 设置companyId
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        Long roleId = sceneRoleId;
        QueryVo queryVo = new QueryVo();
        if (sysDeptService.checkIsCustomer(loginUser.getUser().getDeptId())){
            companyId = sysDeptService.getCustomerId(loginUser.getUser().getDeptId());
            roleId = inspectorRoleId;
        }
        queryVo.filters.put("company_id",companyId);
        queryVo.filters.put("role_id",roleId);
        List<Map<String, Object>> userInfo = pointCheckService.queryUserInfo(queryVo);
        return AjaxResult.success(userInfo);
    }

    @PreAuthorize("@ss.hasPermi('system:point:check:authorize:enum')")
    @GetMapping("/query_authorize_enum")
    public AjaxResult queryAuthorizeEnum(){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        QueryVo queryVo = new QueryVo();
        if (!sysUserService.checkUserIsCommonRole(loginUser.getUser())){
            String sql = customPermissionService.getProjectAuthorizePermission(null, null, loginUser.getUser());
            queryVo.setCustomPermissionSql(sql);
        }
        List<Map<String, String>> projectEnum = pointCheckService.queryAuthorizeEnum(queryVo);
        return AjaxResult.success(projectEnum);
    }
}
